package main

import (
	"fmt"
	redis "pwm/redis_net"
	"strconv"
	"time"

	rpi "github.com/dpawsbear/bear_rpi_go"
)

func main() {
	fmt.Println("starting...")
	if 0 != rpi.Bcm2837_init() {
		rpi.Bcm2837_close()
		panic(55)
		return
	}

	//test for pwm (GPIO.12 and GND)
	rpi.Bcm2837_gpio_fsel(rpi.RPI_3B_GPIO_J8_12, uint8(rpi.BCM2837_GPIO_FSEL_ALT5))

	rpi.Bcm2837_pwm_set_clock(rpi.BCM2837_PWM_CLOCK_DIVIDER_2048)

	rpi.Bcm2837_pwm_set_mode(0, 1, 1)

	rpi.Bcm2837_pwm_set_range(0, 188) //

	rpi.Bcm2837_pwm_set_data(0, 5)

	var sTime int
	sTime = get_redis_conf("stime")

	fmt.Println("starting...sleep time is ", sTime)

	var data uint32 = 5
	var n int = 1
	for {
		sTime = Get_time()
		if sTime < 100 {
			n++
			if n > 3 || sTime < 50 {
				break
			}

		}

		for {
			time.Sleep(time.Millisecond * time.Duration(sTime))
			data++
			if data > 22 {
				break
			}
			rpi.Bcm2837_pwm_set_data(0, data)
		}
		for {
			time.Sleep(time.Millisecond * time.Duration(sTime))
			data--
			if data < 5 {
				data = 5
				break

			}
			rpi.Bcm2837_pwm_set_data(0, data)
		}

	}
}

func get_redis_conf(value_name string) int {

	redis.String_set(value_name, "180")

	fmt.Println("redis set ok")

	value := redis.String_get(value_name)
	//	defer redis.Rs.Close()
	fmt.Println("redis get ok :", value)
	i, err := strconv.Atoi(value)
	if err != nil {
		fmt.Println("strconv.Atoi failed:", err)
	}
	return i

}
func Get_time() int {
	value := redis.String_get("stime")
	i, err := strconv.Atoi(value)
	if err != nil {
		fmt.Println("strconv.Atoi failed:", err)
	}
	return i
}
